﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LCUV;
using System.Globalization;
using System.Data;
using Telerik.Web.UI;
using Oracle.DataAccess.Client;

namespace sWarranty
{
    public partial class SchemeMgr : System.Web.UI.Page
    {

        public string _currentUserEmpNo = "";
        public string _currentUserAuthority = "";
        public string _currentUserRegion = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            litData.Text = "";
            _currentUserEmpNo = GetUserLoginEmpNo();
            Session["UrltoFw"] = "SchemeMgr.aspx";

            if (!IsPostBack)
            {
                Session["_schemeID"] = "";
                txtStartDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }

            Entities db = new Entities();
            var i = from t in db.TB_CM_INCENTIVE_MST
                    orderby t.START_DATE ascending
                    select t;
            int dem = 1;
            foreach (var item in i)
            {
                litData.Text += "<tr style='text-align:center;'>";
                litData.Text += "";
                litData.Text += "<td>" + dem + "</td>";
                litData.Text += "<td title=''> <input type='button' style='cursor: hand;' title='Click to view models applied.' class='button' id='btn" + item.SCHEME_ID.ToString() + "' value='" + item.SCHEME_ID.ToString() +
                           "' onclick='javascript:__doPostBack(\"btnAsp\",\"" + item.SCHEME_ID.ToString() + "\");' > <img id='imgLoading" +
                           item.SCHEME_ID + "' src='../images/oader-grey.gif' style='display: none' /></td>";
                litData.Text += "	<td title=''>" + item.SCHEME_NAME + "	</td>";
                litData.Text += "	<td title=''>" + DBAction.GetRegionByID(item.REGION) + "	</td>";
                litData.Text += "	<td title=''>" + item.START_DATE.ToString("yyyy-MM-dd") + "	</td>";
                litData.Text += "	<td title=''>" + item.END_DATE.ToString("yyyy-MM-dd") + "	</td>";
                if (!string.IsNullOrEmpty(item.PURPOSE))
                    litData.Text += "	<td title=''>" + item.SCHEME_NAME + "	</td>";
                else
                    litData.Text += "	<td title=''>	</td>";
                if (item.CLOSE_FLAG.ToLower() == "n")
                    litData.Text += "	<td title=''>  <input type='button' class='button' style='cursor: hand;' value='Import Model' onclick=\"openPopUp('ModelREGxls.aspx?s=" + item.SCHEME_ID + "','open')\"/>  <input type='button' class='button' style='cursor: hand; width: 60px;' value='Closing' onclick=\"showCloseScheme('" + item.SCHEME_ID + "','" + item.PURPOSE + "','" + item.START_DATE.ToString("yyy-MM-dd") + "','" + item.END_DATE.ToString("yyy-MM-dd") + "','" + _currentUserEmpNo + "')\"/>  </td>";
                else
                    litData.Text += "	<td title=''><input type='button' class='button' style='cursor: hand; width: 100px;' value='Closing Info' onclick=\"showClosingInfo('" + item.SCHEME_ID + "')\"/>   </td>"; //
                litData.Text += "</tr>";
                dem++;
            }
            if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"] == "btnAsp")
            {
                btnAsp_Click(null, null);
            }

            if (_currentUserEmpNo != "VN101025" && _currentUserEmpNo != "VN102652" && _currentUserEmpNo != "VN102280")
                Page.ClientScript.RegisterStartupScript(this.GetType(), "lksdjflkjldf", "permissionInfo();", true);

        }

        private void btnAsp_Click(object sender, System.EventArgs e)
        {
            string _scheme_id = Request.Form["__EVENTARGUMENT"].ToString();
            Session["_schemeID"] = _scheme_id;
            txtSchemeIDHiden.Text = _scheme_id;
            if (!string.IsNullOrEmpty(txtInputFind.Value))
                buildtable(_scheme_id, txtInputFind.Value.Trim().ToUpper());
            else
                buildtable(_scheme_id, null);

        }
        protected void buildtable(string _scheme_id, string _model)
        {
            DataTable dt = new DataTable();

            dt = DBAction.runStore("PK_SOM_MST.PR_INCT_MD_INQ", "uiroi", "scheme_id", _scheme_id, "p_model", _model, null, null, null, null, null, null, null, null, null, null, null, null, null, null
                , null, null, null, null, null, null, null, null, null, null, null, null);
            try
            {
                if (dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0]["Error"].ToString()))
                {
                    MessageBox.Show(dt.Rows[0]["Error"].ToString());
                    return;
                }
            }
            catch (Exception)
            {
                //Column 'Error' does not belong to table <-- ko co' loi j va co' data , thi ko lam j
            }
            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();

        }
        protected string GetUserLoginEmpNo()
        {
            string t = "";
            try
            {
                if (Session["UserLoginInfo"] != null)
                {
                    Entities db = new Entities();
                    var u = (TB_USER[])Session["UserLoginInfo"];
                    int _UID = Convert.ToInt32(u.Single().ID);
                    var au = from ft in db.TB_USER_LEVEL
                             where ft.USER_ID == _UID
                             select ft;
                    int _le = Convert.ToInt32(au.Single().LEVEL_ID);
                    var le = from xx in db.TB_LEVEL
                             where xx.ID == _le
                             select xx;
                    _currentUserAuthority = le.Single().REMARK;
                    _currentUserRegion = u.Single().REGION_ID;
                    if (_currentUserRegion != "00")
                    {
                        DBAction.SetSelected(dropRegion, (u.Single().REGION_ID));
                        DBAction.SetSelected(dropRegion2, (u.Single().REGION_ID));
                        dropRegion.Enabled = false;
                        dropRegion2.Enabled = false;
                    }
                    return u.Single().EMPNO;
                }
            }
            catch (Exception)
            {
                t = "";
            }
            return t;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Entities db = new Entities();

            if (string.IsNullOrEmpty(txtSchemeName.Text))
            {
                MessageBox.Show("Please input Scheme Name");
                txtSchemeName.Focus();
                return;
            }
            if (Convert.ToDateTime(txtStartDate.Text) > Convert.ToDateTime(txtEndDate.Text))
            {
                MessageBox.Show("Start Date must lower than End Date");
                txtStartDate.Focus();
                return;
            }
            //string error = (DBAction.RunStore("select pk_som_mst.FN_INCT_MD_UPL_VAL('" + txtSchemeID.Text.Trim() + "','" + txt + "','" + Point + "','" + Amount + "') from dual"));
            DateTime startD = Convert.ToDateTime(txtStartDate.Text);
            DateTime endD = Convert.ToDateTime(txtEndDate.Text);
            string st = "select pk_som_mst.FN_INCT_SCHEME_CRT('" + dropRegion.SelectedValue + "','" + txtSchemeName.Text.Trim() + "','" + txtPurpose.Text.Trim() + "','" + startD.ToString("yyyyMMdd") + "','" + endD.ToString("yyyyMMdd") + "','" + _currentUserEmpNo + "') from dual";
            OracleCommand cmd = DBAction.con.CreateCommand();
            OracleParameter param = new OracleParameter();
            cmd.CommandText = st;
            cmd.CommandType = CommandType.Text;
            var x = cmd.ExecuteScalar();
            string err = x.ToString();
            if (err != "DONE")
            {
                lblError.Visible = true;
                lblError.Text = err;
            }
            else
            {
                lblError.Visible = true;
                lblError.Text = "Save done.";

                //log
                if (DBAction.LogUser == true)
                {
                    TB_CM_SYS_LOG lg = new TB_CM_SYS_LOG();
                    string seq_key = Guid.NewGuid().ToString();
                    string tit = "Register New Scheme";
                    lg = new TB_CM_SYS_LOG();
                    lg.ID = String.Format("{0:u}", DateTime.Now);
                    lg.ENTRY_USER_ID = _currentUserEmpNo;
                    lg.TITLE = tit;
                    lg.SEQ_KEY = seq_key;
                    lg.ACTION1 = "select pk_som_mst.FN_INCT_SCHEME_CRT('" + dropRegion.SelectedValue + "','" + txtSchemeName.Text.Trim() + "','" + txtPurpose.Text.Trim() + "','" + startD.ToString("yyyyMMdd") + "','" + endD.ToString("yyyyMMdd") + "','" + _currentUserEmpNo + "') from dual";
                    lg.REMARK = err;
                    lg.ENTRY_DATE_TIME = DateTime.Now;
                    db.TB_CM_SYS_LOG.AddObject(lg);
                    db.SaveChanges();
                }
            }


        }

        protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "click", " var btn=document.getElementById('btn'); btn.click();", true);
            DataTable dt = new DataTable();

            dt = DBAction.runStore("PK_SOM_MST.PR_INCT_MD_INQ", "uiroi", "scheme_id", txtSchemeIDHiden.Text, "p_model", txtInputFind.Value.Trim().ToUpper(), null, null, null, null, null, null, null, null, null, null, null, null, null, null
                , null, null, null, null, null, null, null, null, null, null, null, null);
            try
            {
                if (dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0]["Error"].ToString()))
                {
                    MessageBox.Show(dt.Rows[0]["Error"].ToString());
                    return;
                }
            }
            catch (Exception)
            {
                //Column 'Error' does not belong to table <-- ko co' loi j va co' data , thi ko lam j
            }
            RadGrid1.DataSource = dt;
        }

        protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            if (e.Column is GridBoundColumn)
            {
                (e.Column as GridBoundColumn).DataFormatString = "<nobr>{0}</nobr>"; //auto width
                if ((e.Column as GridBoundColumn).HeaderText == "POINT" || (e.Column as GridBoundColumn).HeaderText == "AMT")
                {
                    (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                    (e.Column as GridBoundColumn).ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                }
            }
        }
        //===================================================

    }
}